<?php

namespace App\Service;

use App\RedisAgent\SmsAgent;
use GuzzleHttp\Exception\GuzzleException;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Guzzle\ClientFactory;
use function Hyperf\Config\config;

class SmsService {

    #[Inject]
    protected ClientFactory $clientFactory;

    /**
     *  发送短信
     * @param $mobile
     * @return array
     * @throws GuzzleException
     */
    public function send($mobile): array {
        $secretId  = config('apiadmin.sms.sub_mail.app_id');
        $secretKey = config('apiadmin.sms.sub_mail.app_key');

        $client   = $this->clientFactory->create(['verify' => false]);
        $response = $client->get('https://api-v4.mysubmail.com/service/timestamp.json');
        $output   = json_decode($response->getBody()->getContents(), true);

        $smsCode = (new SmsAgent())->getCode(md5($mobile));
        $postData = [
            "appid"        => $secretId,
            "to"           => $mobile,
            "sign_type"    => 'md5',
            "timestamp"    => $output['timestamp'],
            "sign_version" => 2
        ];
        //整理生成签名所需参数
        ksort($postData);

        $tempStr = "";
        foreach ($postData as $key => $value) {
            $tempStr .= $key . "=" . $value . "&";
        }
        $tempStr               = substr($tempStr, 0, -1);
        $postData['signature'] = md5($secretId . $secretKey . $tempStr . $secretId . $secretKey);
        $postData['content'] = "【易联天成】您的验证码为{$smsCode}，五分钟内有效，如非本人操作请忽略。";

        $response = $client->post('https://api-v4.mysubmail.com/sms/send.json', [
            'form_params' => $postData
        ]);
        return json_decode($response->getBody()->getContents(), true);
    }
}
